<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\api\service\groupon\order;

use app\api\model\Order as OrderModel;
use app\api\model\groupon\Task as TaskModel;
use app\api\model\groupon\Goods as GoodsModel;
use app\common\service\BaseService;
use cores\exception\BaseException;

/**
 * 拼团订单支付成功后的回调
 * Class PaySuccess
 * @package app\api\service\groupon\order
 */
class PaySuccess extends BaseService
{
    /**
     * 回调方法
     * @param $order
     * @throws BaseException
     */
    public function onPaySuccess($order)
    {
        // 获取拼团商品信息
        $goodsInfo = $this->getGrouponGoodsInfo($order);
        // 更新拼单记录
        $this->updateTaskInfo($order, $goodsInfo);
        // 累计拼团商品销量 (实际)
        GoodsModel::setIncSales($goodsInfo['groupon_goods_id']);
    }

    /**
     * 更新拼单记录
     * @param $order
     * @param $goodsInfo
     * @return void
     * @throws BaseException
     */
    private function updateTaskInfo($order, $goodsInfo): void
    {
        $taskId = $order['order_source_id'];
        $model = new TaskModel;
        // 如果订单记录中存在来源ID，视为参与拼单
        if ($taskId > 0) {
            $model->updateTaskInfo($taskId, $order['user_id'], $order['order_id']);
            return;
        }
        // 拼团人数 (仅阶梯团传入)
        $stepPeople = $order['order_source_data']['stepPeople'] ?? 0;
        // 创建新拼单
        $taskId = $model->createTask($order['user_id'], $order['order_id'], $goodsInfo, $stepPeople);
        // 将拼单ID记录到订单来源记录ID
        $this->updateOrderSourceId($order, $taskId);
    }

    /**
     * 更新订单来源记录ID
     * @param $order
     * @param int $taskId
     */
    private function updateOrderSourceId($order, int $taskId)
    {
        OrderModel::updateOrderSourceId($order['order_id'], $taskId);
    }

    /**
     * 获取拼团商品信息
     * @param $order
     * @return GoodsModel|array|null
     */
    private function getGrouponGoodsInfo($order)
    {
        $grouponGoodsId = $order['goods'][0]['goods_source_id'];
        return GoodsModel::detail($grouponGoodsId);
    }
}